//
//  WBMainViewController.swift
//  swiftweibo
//
//  Created by ffxk007 on 2017/6/1.
//  Copyright © 2017年 ffxk007. All rights reserved.
//

import UIKit
import SVProgressHUD



//主控制器
class WBMainViewController: UITabBarController {
    //定时器
    fileprivate var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        setUpTimer()
        
        setupNewFeatureView()
        
        ///设置新特性视图
//        setupNewFeatureView()
        
        //设置代理
        delegate = self
        
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        //测试未读数量
//        WBNetworkManger.shared.unreadCount { (count) in
//            print("有\(count)条新微薄")
//        }
        
    }
    
    deinit {
        timer?.invalidate()
        
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    //使用代码控制设备方向，在需要的时候单独处理
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
//      func supportedInterfaceOrirntations() -> UIInterfaceOrientationMask {
//        return .portrait
//    }
    
    @objc fileprivate func userLogin(n:Notification) {
        print("用户登录通知 \(n)")
        
        var when = DispatchTime.now()
        
        
        //判断n.object是否有值，如果有，提示用户重新登录
        if n.object != nil {
            
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            //修改延时时间
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            //展现登录控制器,通常会和UINAV一起连用
            let nav = UINavigationController(rootViewController: WBQAuthcONTROLLERViewController())
            self.present(nav, animated: true, completion: nil)

        }
        
    }
    
    //FIXME:没有实现
    @objc fileprivate func composeStatus(){
        print("写微博")
        //测试方向旋转
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor.green
        
        let nav = UINavigationController(rootViewController: vc)
        
        
        present(nav, animated: true, completion: nil)
        
    }
    
    fileprivate lazy var composeButon:UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named:"tab_home"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"tab_home_blue"), for: UIControlState.highlighted)
       return button
    }()

}

extension WBMainViewController {
    fileprivate func setupNewFeatureView() {
        //判断是否登录
        if !WBNetworkManger.shared.userLogin {
            return
        }
        
        //1.检查版本是否更新
        
        //2.如果更新显示新特性，否则显示欢迎
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelComeView.welcomeView()
        
        
        //3.添加视图
        
//        v.frame = view.bounds
        view.addSubview(v)
    }
    
    /// extestion中可以有计算型属性，不会占用储存空间
    /**
     appstore每次升级版本号都需要增加
     组成 主版本号.次版本号.修订版本号
     主版本号：意味着大的修改，使用者也需要做大的适应
     次版本号：意味着小的修改，某些函数或者方法的使用或者参数有变化
     修订版本号：框架或者程序内部bug的修订，不会对使用者造成任何影响
    */
    fileprivate var isNewVersion:Bool{
        
        //去当前的版本号
//        print(Bundle.main.infoDictionary ?? [:])
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        //去保存在document【最理想的保存在用户偏好设置里面】目录中的之前的版本号
        let str = "version"
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent(str)
        let sandboxVersion = (try? String(contentsOfFile: jsonPath)) ?? ""
        
        //将当前版本号保存在沙盒
       try? currentVersion.write(toFile: jsonPath, atomically: true, encoding: .utf8)
        
        //返回两个版本号是否一致
        
        
        return currentVersion != sandboxVersion
//        return currentVersion == sandboxVersion
        //CFBundleShortVersionString
    }
}

extension WBMainViewController:UITabBarControllerDelegate {
    
    /// 将要选择tabbaritem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        print("将要切换到\(viewController)")
        //获取控制器在数组中的索引
        let ind = viewControllers?.index(of: viewController)
//        let index = (viewControllers! as NSArray).index(of: viewController)
        //获取当前索引
        if selectedIndex == 0 && ind == selectedIndex {
            print("点击首页")
            //让表格滚动到顶部
            //获取到控制器
            let nav = viewControllers?[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeController
            //滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            //刷新表格
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
            //清楚tabItem的bageNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        //判断目标控制器是否是UIViewcontroller
        
        return !viewController.isMember(of: UIViewController.self)
    }
}
// MARK: - 时钟相关方法
extension WBMainViewController {
    
    fileprivate func setUpTimer(){
        //时间间隔建议长一些
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    ///时钟出发方法
    @objc fileprivate func updateTimer(){
        
        if !WBNetworkManger.shared.userLogin {
            return
        }
        WBNetworkManger.shared.unreadCount { (count) in
            print("")
            //设置首页tabaritem的提示数字
            self.tabBar.items?[0].badgeValue = count>0 ? "\(count)" : nil
            
            //设置app的badgeNumber从iOS8之后，要用户授权之后才能够显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}


extension WBMainViewController{
    
    
    
    fileprivate func setupComposeButton(){
        tabBar.addSubview(composeButon)
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        
        composeButon.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        composeButon.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
  fileprivate func setupChildControllers(){
    
    //获取沙河json路径
    let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
    var data = NSData(contentsOfFile:jsonPath)
    
    if data == nil {
        let path = Bundle.main.path(forResource: "main.json", ofType: nil)
        data = NSData(contentsOfFile: path!)
    }
    //data一定会有一个内容，反序列化
    //从boundle加载配置文件
    guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]]

    else {
        return
    }
    
     //遍历数组，循环创建控制器数组
    var arrayM = [UIViewController]()
    for dict in array! {
        arrayM.append(controller(dict: dict))
    }
    //设置tabbar上网子控制器
    viewControllers = arrayM
    
}
    
    //使用字典创建一个子控制器
    private func controller(dict:[String:AnyObject]) -> UIViewController {
        //取得字典内容
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let cls = NSClassFromString(Bundle.main.nameSpace1 + "." + clsName) as? WBBaseViewController.Type,
              let visitorDict = dict["visitorInfo"] as? [String:String]
            
            else {
               
                return UIViewController()
        }
        
        //创建视图控制器
        //将clsname转换成
        let vc = cls.init()
        vc.title = title
        
        //设置控制器的访客信息的字典
        vc.visitorInfoDic = visitorDict
        
        vc.tabBarItem.image = UIImage(named: "tab_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tab_" + imageName + "blue")?.withRenderingMode(.alwaysOriginal)
        //设置tab的标题字体颜色
//        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
//        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 25)], for: UIControlState(rawValue: 0))
        
        let nav = WBNagationController.init(rootViewController: vc)
        return nav
    }
    
        
}
//extension 类似于OC中的分类，在swift中还可以用来分割代码块
// 可以把功能相似的函数，放在一个extension中
//便于维护代码
//注意：和OC的分类一样，extension中不能定义属性
// MARK: - 设置界面
